package com.byzk.p2p.admin.money.controller;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.byzk.p2p.admin.bank.dto.BankCard;
import com.byzk.p2p.admin.bank.service.BankCardService;
import com.byzk.p2p.admin.base.controller.AdminBaseController;
import com.byzk.p2p.admin.base.util.BaseUtil;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.money.dto.OfflineRecharge;
import com.byzk.p2p.admin.money.dto.RechargeRecord;
import com.byzk.p2p.admin.money.dto.WithdrawRecord;
import com.byzk.p2p.admin.money.service.FundRecordService;
import com.byzk.p2p.admin.money.service.RechargeService;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.money.util.PayMethod;
import com.byzk.p2p.admin.money.util.RechargeStatus;
import com.byzk.p2p.admin.money.util.WithdrawStatus;
import com.byzk.p2p.admin.money.vo.OfflineRechargeVo;
import com.byzk.p2p.admin.money.vo.RechargeRecordVo;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserService;

@Controller
@RequestMapping("/admin/recharge")
public class RechargeController extends AdminBaseController {

	@Autowired
	private RechargeService rechargeService;
	@Autowired
	private UserAccountService accountService;
	@Autowired
	private FundRecordService fundService;
	@Autowired
	private UserService userService;
	@Autowired
	private BankCardService bankCardService;
	
	/**
	 * 充值列表
	 * @param model 视图对象
	 * @param index 当前页
	 * @param limit 每页条数
	 * @param status 提现状态
	 * @param username 用户名
	 * @param match 匹配符号 EQ("="), GT(">"), LT("<"), GE(">="), LE("<="), NE("<>")
	 * @param money 提现金额
	 * @param createTimeBegin 充值时间，开始
	 * @param createTimeEnd 充值时间，结束
	 * @return
	 */
	@RequestMapping("/list")
	public String listRechage(Model model,
							@RequestParam(value="index",required=false,defaultValue="1") int index,
							@RequestParam(value="limit",required=false,defaultValue="10") int limit,
							@RequestParam(value="username",required=false) String username,
							@RequestParam(value="match",required=false) String match,
							@RequestParam(value="method",required=false) String method,
							@RequestParam(value="money",required=false) Double money,
							@RequestParam(value="createTimeBegin",required=false)String createTimeBegin,
						    @RequestParam(value="createTimeEnd",required=false)String createTimeEnd,
						    @RequestParam(value="isOffLine",required=false)String isOffLine,
						    @RequestParam(value="status",required=false)String status) throws Exception{
		RechargeRecordVo rechargeRecordVo = new RechargeRecordVo();
		rechargeRecordVo.setIndex(index);
		rechargeRecordVo.setLimit(limit);
		if (StringUtils.isNotBlank(username)) {
			rechargeRecordVo.setMatchUser(username);
			model.addAttribute("username", username);
		}
		if (StringUtils.isNotBlank(status)) {
			rechargeRecordVo.setStatus(status);
			model.addAttribute("status", status);
		}
		if (StringUtils.isNotBlank(match)) {
			if (match.equals("EQ")) {
				rechargeRecordVo.setMatchEQ(match);
			}else if (match.equals("GT")) {
				rechargeRecordVo.setMatchGT(match);
			}else if (match.equals("LT")) {
				rechargeRecordVo.setMatchLT(match);
			}else if (match.equals("GE")) {
				rechargeRecordVo.setMatchGE(match);
			}else if (match.equals("LE")) {
				rechargeRecordVo.setMatchLE(match);
			}else if (match.equals("NE")) {
				rechargeRecordVo.setMatchNE(match);
			}
			model.addAttribute("match", match);
		}
		if (money != null) {
			rechargeRecordVo.setMoney(money);
			model.addAttribute("money", money);
		}
		if (StringUtils.isNotBlank(createTimeBegin)) {
			rechargeRecordVo.setPublishTimeStart(DateUtils.getRealDate(DateUtils.convert(createTimeBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("createTimeBegin", createTimeBegin);
		}
		if (StringUtils.isNotBlank(createTimeEnd)) {
			rechargeRecordVo.setPublishTimeEnd(DateUtils.getFullDate(DateUtils.convert(createTimeEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("createTimeEnd", createTimeEnd);
		}
		if (StringUtils.isNotBlank(isOffLine)&&"1".equals(isOffLine)) {
			rechargeRecordVo.setIsOffLine("1");
			model.addAttribute("isOffLine", isOffLine);
		}
		rechargeRecordVo.setPayMethod(method);
		model.addAttribute("username", username);
		model.addAttribute("match", match);
		model.addAttribute("money", money);
		model.addAttribute("createTimeBegin", createTimeBegin);
		model.addAttribute("createTimeEnd", createTimeEnd);
		model.addAttribute("method", method);
		PageInfo<RechargeRecordVo> pageInfo = rechargeService.listByMethod(rechargeRecordVo);
		model.addAttribute("pageInfo", pageInfo);
		return ftl(Thread.currentThread().getStackTrace());
	}

	/**
	 * 线下充值列表
	 * @param model 视图对象
	 * @param index 当前页
	 * @param limit 每页条数
	 * @param username 用户名
	 * @param match 匹配符号 EQ("="), GT(">"), LT("<"), GE(">="), LE("<="), NE("<>")
	 * @param money 提现金额
	 * @return
	 */
	@RequestMapping("/offline/list")
	public String listOffline(Model model,
							@RequestParam(value = "index", required = false, defaultValue = "1") int index,
							@RequestParam(value = "limit", required = false, defaultValue = "10") int limit,
							@RequestParam(value="username",required=false) String username,
							@RequestParam(value="match",required=false) String match,
							@RequestParam(value="money",required=false) Double money) {
		OfflineRechargeVo offlineRechargeVo = new OfflineRechargeVo();
		offlineRechargeVo.setIndex(index);
		offlineRechargeVo.setLimit(limit);
		if (StringUtils.isNotBlank(username)) {
			offlineRechargeVo.setMatchUser(username);
			model.addAttribute("username", username);
		}
		if (StringUtils.isNotBlank(match)) {
			if (match.equals("EQ")) {
				offlineRechargeVo.setMatchEQ(match);
			}else if (match.equals("GT")) {
				offlineRechargeVo.setMatchGT(match);
			}else if (match.equals("LT")) {
				offlineRechargeVo.setMatchLT(match);
			}else if (match.equals("GE")) {
				offlineRechargeVo.setMatchGE(match);
			}else if (match.equals("LE")) {
				offlineRechargeVo.setMatchLE(match);
			}else if (match.equals("NE")) {
				offlineRechargeVo.setMatchNE(match);
			}
			model.addAttribute("match", match);
		}
		if (money != null) {
			offlineRechargeVo.setMoney(money);
			model.addAttribute("money", money);
		}
		PageInfo<OfflineRecharge> pageInfo = rechargeService.listOffline(offlineRechargeVo);
		model.addAttribute("pageInfo", pageInfo);
		return ftl(Thread.currentThread().getStackTrace());
	}

	@RequestMapping("/offline/add")
	public String addOffline(@RequestParam(value = "id", required = false) int id) {
		try {
			OfflineRecharge off = rechargeService.getById(id);
			RechargeRecord record = new RechargeRecord();
			record.setCode(off.getOrderCode());
			record.setBalance(off.getBalance());
			record.setCreateTime(new Date());
			record.setFee(off.getFee());
			record.setMoney(off.getMoney());
			record.setPayMethod(off.getMethod());
			record.setStatus(RechargeStatus.WAITING);
			record.setUserId(off.getUserId());
			record.setTerminal("PC");
			Integer temp = rechargeService.saveOrUpdate(record);
			if (temp > 0) {
				off.setIsRecharge("Y");
				rechargeService.updateOffline(off);
				super.printJSON(new JsonMsg(-1, "操作成功", null));
			} else {
				super.printJSON(new JsonMsg(1, "操作失败", null));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 后台手动充值
	 * @param uid 用户id
	 * @param amount 充值金额
	 * @return
	 */
	@RequestMapping("/record/add")
	public String addRechargeRecord(@RequestParam(value = "uid") int uid,@RequestParam(value = "amount") double amount) {
		try {
			RechargeRecord record = new RechargeRecord();
			record.setCode(BaseUtil.generateCode(BaseUtil.CHONGZHI));
			record.setBalance(amount);
			record.setCreateTime(new Date());
			record.setFee(0.0);
			record.setMoney(amount);
			record.setPayMethod(PayMethod.SHOUDONG);
			record.setStatus(RechargeStatus.WAITING);
			record.setUserId(uid);
			record.setTerminal("PC");
			Integer temp = rechargeService.saveOrUpdate(record);
			if (temp > 0) {
				super.printJSON(new JsonMsg(-1, "操作成功", null));
			} else {
				super.printJSON(new JsonMsg(1, "操作失败", null));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 审核手动充值记录
	 * @param isPass 是否通过
	 * @param rechargeRecordId 手动充值记录id
	 * @param verifyRemark 审核备注
	 * @throws Exception
	 */
	@RequestMapping(value="/auditRechargeRecord")
	public void auditRechargeRecord(@RequestParam(value="isPass")Boolean isPass,
									@RequestParam(value="rechargeRecordId") Integer rechargeRecordId,
									@RequestParam(value="verifyRemark")String verifyRemark) throws Exception{
		Integer verifyUserId = getUserId();
		if (verifyUserId == null) {
			printJSON(new JsonMsg(0, "请先登录！"));
			return;
		}
		if (StringUtils.isBlank(verifyRemark)) {
			printJSON(new JsonMsg(1, "请填写审核备注！"));
			return;
		}
		RechargeRecord rechargeRecord = rechargeService.selectById(rechargeRecordId);
		if (rechargeRecord == null) {
			printJSON(new JsonMsg(1, "审核失败！"));
			return;
		}
		rechargeRecord.setVerifyUser(verifyUserId);
		rechargeRecord.setVerifyTime(new Date());
		rechargeRecord.setVerifyRemark(verifyRemark);
		Integer i = 0;
		if (isPass) {
			rechargeRecord.setStatus(RechargeStatus.SUCCESS);
			i = rechargeService.saveOrUpdate(rechargeRecord);
			UserAccount account=accountService.getByUserId(rechargeRecord.getUserId());
			account.setBalance(account.getBalance()+rechargeRecord.getMoney());
			account.setTotalAmount(account.getTotalAmount()+rechargeRecord.getMoney());
			account.setTotalRecharge(account.getTotalRecharge()+rechargeRecord.getMoney());
			account.setTotalIncome(account.getTotalIncome()+rechargeRecord.getMoney());
			
			fundService.addFundRecord(rechargeRecord.getUserId(), rechargeRecord.getMoney(), 0.0, "PC", "后台手动充值", FundRecordType.Type.RECHARGE.index,0.0);
			
			accountService.saveOrUpdate(account);
		}else{
			rechargeRecord.setStatus(RechargeStatus.FAILURE);
			i = rechargeService.saveOrUpdate(rechargeRecord);
		}
		if (i > 0) {
			printJSON(new JsonMsg(-1, "审核成功！"));
			return;
		}else{
			printJSON(new JsonMsg(1, "审核失败！"));
			return;
		}
	}
	

	/**
	 * Description:打开线下充值页面
	 * @auther:fdq
	 * @date :2016年10月20日
	 */
	@RequestMapping(value = "/offLineRecharge")
	public String offLineRecharge(){
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * Description:线下充值确认
	 * @auther:fdq
	 * @date :2016年10月20日
	 */
	@RequestMapping(value = "/offLineRechargeSubmit")
	public void offLineWithdrawSubmit(@RequestParam(value="username",required=true) String username,
			@RequestParam(value="ssnCode",required=true) String ssnCode,
			@RequestParam(value="money",required=true) double money){
		try {
			User user=userService.getByName(username);
			if(null == user){
				super.printJSON(new JsonMsg(1, "线下充值失败!不存在该用户！"));
				return;
			}
			
			int i =  rechargeService.addRecharge(ssnCode,user.getId(), money,"线下充值","1");
			if(i==0){
				super.printJSON(new JsonMsg(-1, "线下充值成功!"));
			}else{
				super.printJSON(new JsonMsg(1, "线下充值失败!"));
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
